package cn.itcast.service;


import cn.itcast.pojo.User;
import cn.itcast.pojo.UserInfo;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;



@Service
public class MyUserDetailsService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        //这里可以可以通过username（登录时输入的用户名）然后到数据库中找到对应的用户信息，并构建成我们自己的UserInfo来返回。
        User user = userService.findUserByUsername(username);

        if (user == null) {
            return null;
        }

        List<String> roleList = userService.findRoleByUsername(username);
        //System.out.println("roleList = " + roleList);
        if (!(roleList.size() > 0 && roleList != null) ) {
            roleList = Collections.emptyList();
        }
        List<String> permissionList = userService.findPermissionByUsername(username);
        if (!(permissionList.size() > 0 && permissionList != null) ) {
            permissionList = Collections.emptyList();
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setRoleList(roleList);
        userInfo.setPermissionList(permissionList);
        userInfo.setPassword(user.getPassword());
        userInfo.setUsername(user.getUsername());
        userInfo.setId(user.getId());

        /*User byUsername = userService.findByUsername(user.getUsername());
        System.out.println(byUsername);*/

        return userInfo;
    }
}
